//Copyright 2008 by Wes Corp for Trafficman  All rights reserved.abstract 

package org.trafficman.trafficman_main;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;


public class TrafficmanFileDLDefaultLocalService extends Service {
	private NotificationManager mNM;
	private TrafficmanFileServerNotesDbAdapter default_Server_mDbHelper;

	/**
	 * Class for clients to access. Because we know this service always runs in
	 * the same process as its clients, we don't need to deal with IPC.
	 */
	public class LocalBinder extends Binder {
		TrafficmanFileDLDefaultLocalService getService() {
			return TrafficmanFileDLDefaultLocalService.this;
		}
	}

	@Override
	protected void onCreate() {
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		// Display a notification about us starting. We put an icon in the
		// status bar.
		showNotification();

		download_File_List();

		stopService(new Intent(this, TrafficmanFileDLDefaultLocalService.class));

		onDestroy();
		
	}

	private void download_File_List() {
		try {
			
			//get the current server informations			
			
			
//			Constants.CURRENT_JV_SERVER_TITLE = result.getString(columnID2);
//			Constants.CURRENT_JV_SERVER_URL = result.getString(columnID3);
//			Constants.CURRENT_JV_SERVER_USER = result.getString(columnID4);
//			Constants.CURRENT_JV_SERVER_PASS = result.getString(columnID5);
			
			//String outFilename = "/data/data/com.meridianhouseplans.jobview2/databases/db_dl_test";
			String outFilename = TrafficmanConstants.DEFAULT_FILE_LOCATION + "/" + TrafficmanConstants.NAME_CURRENT_SERVER_FILES;
			
			OutputStream out = new FileOutputStream(outFilename);

			//String url_string = Constants.CURRENT_JV_SERVER_URL + "?" + "username=" + Constants.CURRENT_JV_SERVER_USER  + "password=" + Constants.CURRENT_JV_SERVER_PASS;
			//URL url = new URL("http://169.254.116.166/jobview2/index2.php?lastname=32lkjljh&firstname=ljkhlkjh&phone=lkjhlkhj");
			URL url = new URL(TrafficmanConstants.CURRENT_JV_SERVER_URL);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setReadTimeout(1000);
			http.setConnectTimeout(1000);
			http.setRequestMethod("GET");
			http.connect();
			responce = http.getResponseCode();
			if (responce == HttpURLConnection.HTTP_OK) {
				InputStream in = http.getInputStream();

				// convert the input byte stream to file
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
					String msg = buf.toString();
					Log.d("hello", msg);
				}
				out.close();
				in.close();
			}
			http.disconnect();
			download_success = 1;

			//stopService(new Intent(this, LocalService.class));

		} catch (Exception e) {
			Log.e("File Download", e.toString(), e);
			download_success = 0;
			//stopService(new Intent(this, LocalService.class));
		}
		//stopService(new Intent(this, LocalService.class));

	}

	@Override
	protected void onDestroy() {
		// Cancel the persistent notification.
		mNM.cancel(R.string.jv_dl_started);

		// Tell the user we stopped.
		if (download_success == 1) {
			Toast.makeText(this, R.string.jv_dl_df_success, Toast.LENGTH_SHORT)
					.show();
		} else {
			Toast.makeText(this, R.string.jv_dl_df_failure, Toast.LENGTH_SHORT)
					.show();
		}
		
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	// This is the object that receives interactions from clients. See
	// RemoteService for a more complete example.
	private final IBinder mBinder = new LocalBinder();
	private int responce;
	private int download_success;

	/**
	 * Show a notification while this service is running.
	 */
	private void showNotification() {
		// This is who should be launched if the user selects our notification.
		Intent contentIntent = new Intent(this, TrafficmanLocalServiceController.class);

		// This is who should be launched if the user selects the app icon in
		// the notification,
		// (in this case, we launch the same activity for both)
		Intent appIntent = new Intent(this, TrafficmanLocalServiceController.class);

		// In this sample, we'll use the same text for the ticker and the
		// expanded notification
		CharSequence text = getText(R.string.jv_dl_started);

		mNM.notify(R.string.jv_dl_started, // we use a string id
				// because it is a unique
				// number. we use it later to cancel the
				// notification
				new Notification(this, // our context
						R.drawable.stat_sample, // the icon for the status bar
						text, // the text to display in the ticker
						System.currentTimeMillis(), // the timestamp for the
						// notification
						getText(R.string.jv_label), // the title for
						// the
						// notification
						text, // the details to display in the notification
						contentIntent, // the contentIntent (see above)
						R.drawable.app_sample_code, // the app icon
						getText(R.string.activity_sample_code), // the name of
						// the app
						appIntent)); // the appIntent (see above)
	}

	private void download_Default_Server_JobView_File_List() {
		try {
			download_success = -1;
			String outFilename = "/data/data/com.meridianhouseplans.jobview2/databases/db_dl_test";
			OutputStream out = new FileOutputStream(outFilename);

			URL url = new URL("http://169.254.116.166/android/db_dl_test");
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setReadTimeout(1000);
			http.setConnectTimeout(1000);
			http.setRequestMethod("GET");
			http.connect();
			responce = http.getResponseCode();
			if (responce == HttpURLConnection.HTTP_OK) {
				InputStream in = http.getInputStream();

				// convert the input byte stream to file
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.close();
				in.close();
			}
			http.disconnect();
			download_success = 1;

			//stopService(new Intent(this, LocalService.class));

		} catch (Exception e) {
			Log.e("File Download", e.toString(), e);
			download_success = 0;
			//stopService(new Intent(this, LocalService.class));
		}
		//stopService(new Intent(this, LocalService.class));

	}
}
